package com.zyg.manager.service.impl;

import com.zyg.manager.entity.vo.ItemCatVoEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.common.utils.PageUtils;
import com.zyg.common.utils.Query;

import com.zyg.manager.dao.ItemCatDao;
import com.zyg.manager.entity.ItemCatEntity;
import com.zyg.manager.service.ItemCatService;


@Service("itemCatService")
public class ItemCatServiceImpl extends ServiceImpl<ItemCatDao, ItemCatEntity> implements ItemCatService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ItemCatEntity> page = this.page(
                new Query<ItemCatEntity>().getPage(params),
                new QueryWrapper<ItemCatEntity>()
        );
        List<ItemCatVoEntity> collect = page.getRecords().stream().map(m -> {
            //1. 定义ItemCatVoEntity对象
            ItemCatVoEntity voEntity = new ItemCatVoEntity();
            //2. 将m对象拷贝到ItemCatVoEntity中
            BeanUtils.copyProperties(m, voEntity);
            //3. 得到parentId
            Long parentId = m.getParentId();
            ItemCatEntity parentItemCat = this.getById(parentId==0?m.getId():parentId);
            voEntity.setParentName(parentItemCat.getName());
            return voEntity;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);
        return pageUtils;
    }

    // 查询所有分类
    @Override
    public List<ItemCatEntity> findAll() {
        //1. 查询一级分类
        List<ItemCatEntity> oneItemCats = this.list(new QueryWrapper<ItemCatEntity>().eq("parent_id", 0));
        //2. 查询二级分类
        for (ItemCatEntity oneItemCat : oneItemCats) {
            oneItemCat.setChildren(new ArrayList<>());
            findItemCats(this.list(),oneItemCat);
        }


        System.out.println(oneItemCats);
        return oneItemCats;
    }

    //2. 根据一级分类查询二级、三级分类
    private void findItemCats(List<ItemCatEntity> list, ItemCatEntity oneItemCat) {
        //2.1 为父节点指定集合
        oneItemCat.setChildren(new ArrayList<>());
        //2.2 遍历子节点，判断并得到此子节点下的所有的子节点集合
        for (ItemCatEntity entity : list) {
            //2.3 判断某个子节点是否是指定的父节点下的子节点
            if(oneItemCat.getId().longValue() == entity.getParentId().longValue()){
                //2.3.1 如果发现是此子节点下的子节点添加到此子节点集合中
                oneItemCat.getChildren().add(entity);
                //2.3.2 递归此子节点，然后进行下一轮的寻找此子点的过程
                findItemCats(list,entity);
            }
        }

    }

}